package com.zz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zz.common.R;
import com.zz.entity.ApplicationAuditing;
import com.zz.entity.Attended;
import com.zz.entity.Box;
import com.zz.entity.Investigation;
import com.zz.mapper.ApplicationAuditingMapper;
import com.zz.mapper.AttendedMapper;
import com.zz.mapper.BoxMapper;
import com.zz.mapper.InvestigationMapper;
import com.zz.service.InvestigationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
@Slf4j
public class InvestigationServiceImpl extends ServiceImpl<InvestigationMapper, Investigation> implements InvestigationService {

    @Autowired
    private InvestigationMapper investigationMapper;

    @Autowired
    private ApplicationAuditingMapper applicationAuditingMapper;

    @Autowired
    private AttendedMapper attendedMapper;

    @Override
    public R<String> add(Investigation investigation) {
        // 将用户所报名活动状态改为已经填写调查问卷
        int activityId = investigation.getActivityId();
        int userId = investigation.getId();

        LambdaQueryWrapper<Attended> attendedWrapper = new LambdaQueryWrapper<>();
        attendedWrapper.eq(Attended::getUserId, userId).eq(Attended::getActivityId, activityId);
        Attended attended = attendedMapper.selectOne(attendedWrapper);
        if (attended.getIfInvestigated() == 1){
            return R.error("此用户已经填写此活动调查问卷！");
        }
        attended.setIfInvestigated(1);

        // 更新数据库信息
        attendedMapper.updateById(attended);
        investigationMapper.insert(investigation);

        return R.success("新增调查成功！");
    }


    /**
     * 调查问卷分页展示
     * 周紫
     * */
    @Override
    public R<Page> page(int page, int pageSize, int activityId) {

        // 构造分页构造器
        Page<Investigation> pageInfo = new Page<>(page, pageSize);

        // 构造条件构造器
        LambdaQueryWrapper<Investigation> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Investigation::getActivityId, activityId);

        // 执行分页查询
        // 在page方法内部会将查好的数据封装，赋好值给pageInfo
        Page<Investigation> investigationPage = investigationMapper.selectPage(pageInfo, queryWrapper);

        return R.success(investigationPage);
    }
}
